package com.itheima.reggie.contreller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码为--->:{}",code);
            session.setAttribute(phone,code);
            return R.success("验证码发送成功");
        }
        return R.error("验证码发送失败");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String,String> map,HttpSession session){
        //用户的手机号
        String phone = map.get("phone");
        //用户的验证码
        String userCode = map.get("code");
        //发送的验证码
        String code = (String) session.getAttribute(phone);
        //判断验证码是否一致
        if (!code.equals(userCode)||StringUtils.isEmpty(code)){
            return R.error("验证码错误");
        }
       // 判断是否是老用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        User user = userService.getOne(queryWrapper);
        if (user==null){
             user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }else{

            if (user.getStatus()==0){
                return R.error("用户已被禁用");
            }
        }
        session.removeAttribute("code");
        session.setAttribute("user",user.getId());
        return R.success("登录成功");
    }
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("");
    }
}
